<template>
  <div class="app-container flex dirc">
    <!-- 基础信息 -->
    <el-card shadow="hover">
      <template #header>
        <span>合同信息</span>
        <el-button v-if="designStatus == ContractDesignStatus.CONFIRM" @click="handleDownload" class="ml10"
          type="primary" size="small">
          设计清单下载
        </el-button>
      </template>
      <el-descriptions v-if="formData">
        <el-descriptions-item label="合同名称">{{ formData.name }}</el-descriptions-item>
        <el-descriptions-item label="关联客户">
          {{ formData.customerId }}
        </el-descriptions-item>
        <el-descriptions-item label="甲方">{{ formData.partyA }}</el-descriptions-item>
        <el-descriptions-item label="乙方">{{ formData.partyB }}</el-descriptions-item>
        <el-descriptions-item label="总金额">{{ `￥${formData.amount}` }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ `${Contract_Status_Label[formData.status]}` }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="flex1 mt10 full" shadow="hover">
      <template #header>
        <span>设计清单</span>
      </template>
      <el-table ref="dataTableRef" v-loading="loading" :data="contractItems" height="calc(100% - 40px)"
        highlight-current-row v-if="formData">
        <el-table-column label="材料名称" prop="name" />
        <el-table-column label="材料类型" width="120">
          <template #default="scope">
            {{ SaleMealTypeLabel[scope.row.itemType] }}
          </template>
        </el-table-column>
        <el-table-column label="规格" prop="spec" />
        <el-table-column label="单位" prop="unit" />
        <el-table-column label="数量" align="center" prop="quantity">
          <template #default="scope" v-if="formData.status === ContractStatus.FIRST_SIGN">
            <el-input-number v-model="scope.row.quantity" style="width: 150px" :min="0" />
          </template>
        </el-table-column>
        <el-table-column label="单价" align="right" prop="price">
          <template #default="scope">
            {{ `￥${scope.row.price}` }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="100" align="center">
          <template #default="scope">
            <el-button size="small" type="danger" link @click="handleDeleteItem(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt10 disf alc juc" v-if="formData && formData.status == ContractStatus.FIRST_SIGN">
        <el-button class="ml10" type="primary" plain @click="showMaterialWindow()">
          添加材料
        </el-button>
        <el-button class="ml10" type="primary" plain @click="handleEditMaterial(true)">
          保 存
        </el-button>
        <el-button class="ml10" type="primary" @click="handleToSign">确认设计，去签字</el-button>
      </div>
    </el-card>
    <!-- 弹窗：预览&签订 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="70%" top="5vh" @close="closeWindow">
      <SignQrCode :id="contractId" />
      <template #footer>
        <el-button type="primary" @click="handleSignComplete">完成设计</el-button>
        <el-button @click="closeWindow">取消</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗：选材料-->
    <el-dialog v-model="chooseMaterialVisible" title="选择材料" width="800px" @close="closeMaterialWindow">
      <MaterialSelector ref="materialRef" :withNorm="true" operation="add" @addItem="addMaterial" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseMaterialDone">确 定</el-button>
          <el-button @click="closeMaterialWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { MaterialPageVO } from "@/api/business/material/material.api";
import MaterialSelector from "@/views/business/material/material/MaterialSelector.vue";
import { SaleMealTypeLabel } from "@/api/business/material/sealMeal.api";
import SignQrCode from "./components/signQr.vue";
import ContractAPI, {
  ContractItem,
  ContractPageVO,
  ContractStatus,
  Contract_Status_Label,
} from "@/api/flow/contract.api";
import { cloneDeep } from "lodash-es";
import ContractDesignAPI, { ContractDesignStatus } from "@/api/flow/contractDesign.api";


defineOptions({
  name: "DesignEdit",
  inheritAttrs: false,
});

const route = useRoute();
const id = ref("");
const contractId = ref("");
const loading = ref(false);
const formData = ref<ContractPageVO>(); //合同信息
const contractItems = ref<ContractItem[]>([]); //合同材料列表
const designStatus = ref("");
const materialRef = ref();
const chooseMaterialVisible = ref(false);

onActivated(() => {
  if (route.query.id == id.value && route.query.contractId == contractId.value) return;
  // id变动 重置数据
  id.value = route.query.id as string;
  contractId.value = route.query.contractId as string;
  loadContractDetail();
});

const loadContractDetail = async () => {
  if (!contractId.value || contractId.value === "0") {
    return;
  }
  await ContractAPI.getDetail(contractId.value).then((data) => {
    formData.value = { ...data };
    contractItems.value = cloneDeep(data.items);
  });
  await ContractDesignAPI.loadById(id.value).then((data) => {
    designStatus.value = data.status;
  });
};

// 提交编辑
async function handleEditMaterial(showMsg: boolean = false) {
  loading.value = true;
  // 处理数据
  try {
    await ContractDesignAPI.reviewContract({
      id: contractId.value,
      items: contractItems.value,
    });
    showMsg && ElMessage.success("保存成功");
    loadContractDetail();
  } catch (error) {
    console.error("保存失败");
  }
  loading.value = false;
}

// 设计确认-完成签约
function handleSignComplete() {
  closeWindow();
  ElMessage.success("设计确认成功");
  loadContractDetail();
}

// 合同下载
async function handleDownload() {
  await ContractDesignAPI.download(contractId.value);
}

/**
 * 签订弹窗
 */
const dialog = reactive({
  title: "设计确认",
  visible: false,
});
async function handleToSign() {
  await handleEditMaterial();
  dialog.visible = true;
}
function closeWindow() {
  dialog.visible = false;
}

function showMaterialWindow() {
  chooseMaterialVisible.value = true;
  nextTick(() => {
    materialRef.value.handleQuery();
  });
}

function chooseMaterialDone() {
  chooseMaterialVisible.value = false;
}

function closeMaterialWindow() {
  chooseMaterialVisible.value = false;
}

/**
 * 添加材料
 */
async function addMaterial(item: MaterialPageVO) {
  const oMeal = contractItems.value.find((m) => m.resourceId === item.id);
  if (oMeal) {
    oMeal.quantity++;
  } else {
    contractItems.value.push({
      resourceId: item.id,
      quantity: 1,
      name: item.name,
      price: item.price,
      unit: item.unit,
      itemType: item.type,
      remark: "",
      spec: item.spec,
    });
  }
}

// 删除材料
function handleDeleteItem(item: ContractItem) {
  contractItems.value = contractItems.value.filter((i) => i.id !== item.id);
}

</script>

<style lang="scss" scoped></style>
